
/**
 * 请求class
 */
class CommonUtil {

  private static BASE_URL:string = import.meta.env.VUE_APP_BASE_API

  /**
   * 获取formData
   * @param data 
   * @param formData 
   * @param parentKey
   * @returns 
   */
  public static getFormData(data:Record<string, any>, formData: FormData = new FormData(),
  parentKey: string = ''): FormData {

    for (const key in data) {
      if (!data.hasOwnProperty(key)) {
        continue;
      }

      const value = data[key];
      const constructedKey = parentKey ? `${parentKey}.${key}` : key;

      if (value === null || value === undefined) {
        continue;
      } else if (value instanceof Date) {
        formData.append(constructedKey, value.toISOString());
      } else if (this.isFile(value)) {
        // 处理文件对象
        formData.append(constructedKey, value instanceof File ? value : value.raw);
      } else if (Array.isArray(value)) {
        value.forEach((item, index) => {
          const arrayKey = `${constructedKey}[${index}]`;
          if (this.isFile(item)) {
            // 处理文件对象
            formData.append(constructedKey, (item as { raw: File }).raw);
          } else if (typeof item === 'object' && item !== null) {
            CommonUtil.getFormData(item, formData, arrayKey);
          } else {
            formData.append(arrayKey, String(item));
          }
        });
      } else if (typeof value === 'object' && !this.isBlob(value)) {
        CommonUtil.getFormData(value, formData, constructedKey);
      } else {
        formData.append(constructedKey, String(value));
      }
    }

    return formData;
  }

   /**
   * 检查是否是文件对象
   */
   private static isFile(value: any): value is File | { raw: File } {
    return value instanceof File || 
        (typeof value === 'object' && 
        value !== null && 
        'name' in value && 
        'raw' in value  );
  }

  /**
   * 检查是否是Blob对象
   */
  private static isBlob(value: any): value is Blob {
    return value instanceof Blob;
  }

  public static getRequestPath(): string { 
    // return CommonUtil.BASE_URL || '';
    return window.location.protocol + '//' + window.location.host + import.meta.env.VITE_APP_BASE_API;

  }


public static getParamValue(paramName: string, url?: string): string {
    const targetUrl = url || (typeof window !== 'undefined' ? window.location.href : '');
    if (!targetUrl) return '';

    try {
      const urlObj = new URL(targetUrl);
      return urlObj.searchParams.get(paramName) || '';
    } catch (e) {
      // 兼容非标准URL格式的备用方案
      const regex = new RegExp(`[?&]${paramName}(=([^&#]*)|&|#|$)`);
      const results = regex.exec(targetUrl);
      if (!results || !results[2]) return '';
      return decodeURIComponent(results[2].replace(/\+/g, ' '));
    }
  }
}


export default CommonUtil
